<template>
  <div class="sales-report">
    <div class="page-header">
      <div class="header-left">
        <h2>销售统计</h2>
        <p>销售数据统计分析和趋势监控</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="generateReport">
          <el-icon><Document /></el-icon>
          生成报告
        </el-button>
        <el-button type="success" @click="exportData">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 统计概览 -->
    <div class="stats-overview">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon total">
                <el-icon><ShoppingCart /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ salesStats.totalOrders }}</div>
                <div class="stat-label">总订单数</div>
                <div class="stat-trend up">
                  <el-icon><ArrowUp /></el-icon>
                  +{{ salesStats.orderGrowth }}%
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon revenue">
                <el-icon><Money /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">¥{{ salesStats.totalRevenue }}</div>
                <div class="stat-label">总销售额</div>
                <div class="stat-trend up">
                  <el-icon><ArrowUp /></el-icon>
                  +{{ salesStats.revenueGrowth }}%
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon average">
                <el-icon><TrendCharts /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">¥{{ salesStats.averageOrder }}</div>
                <div class="stat-label">平均订单</div>
                <div class="stat-trend up">
                  <el-icon><ArrowUp /></el-icon>
                  +{{ salesStats.averageGrowth }}%
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon customers">
                <el-icon><User /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ salesStats.totalCustomers }}</div>
                <div class="stat-label">客户数量</div>
                <div class="stat-trend up">
                  <el-icon><ArrowUp /></el-icon>
                  +{{ salesStats.customerGrowth }}%
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <el-card>
        <el-form :model="filterForm" inline>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 250px"
            />
          </el-form-item>
          <el-form-item label="商品分类">
            <el-select
              v-model="filterForm.categoryId"
              placeholder="请选择分类"
              clearable
              style="width: 150px"
            >
              <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="销售渠道">
            <el-select
              v-model="filterForm.channel"
              placeholder="请选择渠道"
              clearable
              style="width: 120px"
            >
              <el-option label="线上" value="online" />
              <el-option label="线下" value="offline" />
              <el-option label="第三方" value="thirdparty" />
            </el-select>
          </el-form-item>
          <el-form-item label="订单状态">
            <el-select
              v-model="filterForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 120px"
            >
              <el-option label="已完成" value="completed" />
              <el-option label="处理中" value="processing" />
              <el-option label="已取消" value="cancelled" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="resetFilter">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 图表分析 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <!-- 销售趋势 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span>销售趋势</span>
            </template>
            <div ref="salesTrendChart" class="chart-container"></div>
          </el-card>
        </el-col>
        
        <!-- 分类销售分布 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span>分类销售分布</span>
            </template>
            <div ref="categorySalesChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>
      
      <el-row :gutter="20" style="margin-top: 20px;">
        <!-- 热销商品排行 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span>热销商品排行</span>
            </template>
            <div ref="hotProductsChart" class="chart-container"></div>
          </el-card>
        </el-col>
        
        <!-- 销售渠道对比 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span>销售渠道对比</span>
            </template>
            <div ref="channelComparisonChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 销售详情表格 -->
    <div class="table-section">
      <el-card>
        <template #header>
          <div class="table-header">
            <span>销售订单记录</span>
            <div class="table-actions">
              <el-button type="primary" size="small" @click="showAddOrder = true">
                <el-icon><Plus /></el-icon>
                新增订单
              </el-button>
              <el-button type="warning" size="small" @click="batchExport">
                <el-icon><Download /></el-icon>
                批量导出
              </el-button>
            </div>
          </div>
        </template>
        
        <el-table
          :data="salesList"
          v-loading="tableLoading"
          style="width: 100%"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="orderCode" label="订单编号" width="120" />
          <el-table-column prop="customerName" label="客户姓名" width="100" />
          <el-table-column prop="productName" label="商品名称" min-width="150" />
          <el-table-column prop="category" label="分类" width="100" />
          <el-table-column prop="quantity" label="数量" width="80" />
          <el-table-column prop="unitPrice" label="单价" width="100">
            <template #default="{ row }">
              ¥{{ row.unitPrice }}
            </template>
          </el-table-column>
          <el-table-column prop="totalAmount" label="总金额" width="120">
            <template #default="{ row }">
              ¥{{ row.totalAmount }}
            </template>
          </el-table-column>
          <el-table-column prop="channel" label="销售渠道" width="100">
            <template #default="{ row }">
              <el-tag :type="getChannelTag(row.channel)">
                {{ getChannelText(row.channel) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="orderDate" label="下单时间" width="180" />
          <el-table-column prop="status" label="订单状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="viewDetail(row)">
                详情
              </el-button>
              <el-button type="warning" size="small" @click="editOrder(row)">
                编辑
              </el-button>
              <el-button type="info" size="small" @click="printOrder(row)">
                打印
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { 
  Document, 
  Download, 
  Search, 
  Refresh, 
  Plus,
  ShoppingCart,
  Money,
  TrendCharts,
  User,
  ArrowUp,
  ArrowDown
} from '@element-plus/icons-vue'

export default defineComponent({
  name: 'SalesReport',
  components: {
    Document,
    Download,
    Search,
    Refresh,
    Plus,
    ShoppingCart,
    Money,
    TrendCharts,
    User,
    ArrowUp,
    ArrowDown
  },
  setup() {
    const tableLoading = ref(false)
    const currentPage = ref(1)
    const pageSize = ref(20)
    const total = ref(0)
    const showAddOrder = ref(false)
    const selectedRecords = ref([])
    
    // 图表引用
    const salesTrendChart = ref(null)
    const categorySalesChart = ref(null)
    const hotProductsChart = ref(null)
    const channelComparisonChart = ref(null)
    
    // 筛选表单
    const filterForm = reactive({
      dateRange: [],
      categoryId: null,
      channel: '',
      status: ''
    })
    
    // 销售统计数据
    const salesStats = reactive({
      totalOrders: 1250,
      orderGrowth: 12.5,
      totalRevenue: '456,800',
      revenueGrowth: 15.8,
      averageOrder: '365.44',
      averageGrowth: 3.2,
      totalCustomers: 856,
      customerGrowth: 8.9
    })
    
    // 分类数据
    const categories = ref([
      { id: 1, name: '生鲜食品' },
      { id: 2, name: '饮料酒水' },
      { id: 3, name: '零食糖果' },
      { id: 4, name: '日用品' },
      { id: 5, name: '电子产品' }
    ])
    
    // 销售列表数据
    const salesList = ref([
      {
        orderCode: 'SO001',
        customerName: '张三',
        productName: '有机苹果',
        category: '生鲜食品',
        quantity: 5,
        unitPrice: 8.5,
        totalAmount: 42.5,
        channel: 'online',
        orderDate: '2024-01-15 10:30:00',
        status: 'completed'
      },
      {
        orderCode: 'SO002',
        customerName: '李四',
        productName: '纯牛奶',
        category: '饮料酒水',
        quantity: 2,
        unitPrice: 12.5,
        totalAmount: 25.0,
        channel: 'offline',
        orderDate: '2024-01-15 09:15:00',
        status: 'completed'
      },
      {
        orderCode: 'SO003',
        customerName: '王五',
        productName: '面包',
        category: '零食糖果',
        quantity: 3,
        unitPrice: 5.8,
        totalAmount: 17.4,
        channel: 'thirdparty',
        orderDate: '2024-01-14 16:45:00',
        status: 'processing'
      },
      {
        orderCode: 'SO004',
        customerName: '赵六',
        productName: '洗发水',
        category: '日用品',
        quantity: 1,
        unitPrice: 45.0,
        totalAmount: 45.0,
        channel: 'online',
        orderDate: '2024-01-14 14:20:00',
        status: 'cancelled'
      }
    ])
    
    // 初始化图表
    const initCharts = () => {
      nextTick(() => {
        // 销售趋势图
        const salesTrend = echarts.init(salesTrendChart.value)
        salesTrend.setOption({
          title: { text: '近30天销售趋势' },
          tooltip: { trigger: 'axis' },
          xAxis: {
            type: 'category',
            data: ['1月1日', '1月5日', '1月10日', '1月15日', '1月20日', '1月25日', '1月30日']
          },
          yAxis: { type: 'value' },
          series: [{
            data: [15000, 18000, 22000, 25000, 28000, 32000, 35000],
            type: 'line',
            smooth: true,
            areaStyle: {}
          }]
        })
        
        // 分类销售分布
        const categorySales = echarts.init(categorySalesChart.value)
        categorySales.setOption({
          title: { text: '分类销售分布' },
          tooltip: { trigger: 'item' },
          series: [{
            type: 'pie',
            radius: '50%',
            data: [
              { value: 150000, name: '生鲜食品' },
              { value: 120000, name: '饮料酒水' },
              { value: 80000, name: '零食糖果' },
              { value: 60000, name: '日用品' },
              { value: 46800, name: '电子产品' }
            ]
          }]
        })
        
        // 热销商品排行
        const hotProducts = echarts.init(hotProductsChart.value)
        hotProducts.setOption({
          title: { text: '热销商品排行' },
          tooltip: { trigger: 'axis' },
          xAxis: { type: 'value' },
          yAxis: { type: 'category', data: ['有机苹果', '纯牛奶', '面包', '洗发水', '牙膏'] },
          series: [{
            data: [1200, 980, 850, 650, 520],
            type: 'bar',
            itemStyle: { color: '#67C23A' }
          }]
        })
        
        // 销售渠道对比
        const channelComparison = echarts.init(channelComparisonChart.value)
        channelComparison.setOption({
          title: { text: '销售渠道对比' },
          tooltip: { trigger: 'axis' },
          xAxis: { type: 'category', data: ['线上', '线下', '第三方'] },
          yAxis: { type: 'value' },
          series: [{
            data: [250000, 150000, 56800],
            type: 'bar'
          }]
        })
      })
    }
    
    // 筛选处理
    const handleFilter = () => {
      currentPage.value = 1
      loadData()
    }
    
    // 重置筛选
    const resetFilter = () => {
      Object.assign(filterForm, {
        dateRange: [],
        categoryId: null,
        channel: '',
        status: ''
      })
      currentPage.value = 1
      loadData()
    }
    
    // 加载数据
    const loadData = async () => {
      tableLoading.value = true
      try {
        // 模拟API请求
        await new Promise(resolve => setTimeout(resolve, 1000))
        total.value = salesList.value.length
      } catch (error) {
        console.error('加载数据失败:', error)
        ElMessage.error('加载数据失败')
      } finally {
                  tableLoading.value = true
      }
    }
    
    // 生成报告
    const generateReport = async () => {
      try {
        ElMessage.success('销售报告生成成功')
      } catch (error) {
        console.error('生成报告失败:', error)
        ElMessage.error('生成报告失败')
      }
    }
    
    // 导出数据
    const exportData = async () => {
      try {
        ElMessage.success('数据导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败')
      }
    }
    
    // 查看详情
    const viewDetail = (row) => {
      ElMessage.info(`查看订单详情: ${row.orderCode}`)
    }
    
    // 编辑订单
    const editOrder = (row) => {
      ElMessage.info(`编辑订单: ${row.orderCode}`)
    }
    
    // 打印订单
    const printOrder = (row) => {
      ElMessage.info(`打印订单: ${row.orderCode}`)
    }
    
    // 批量导出
    const batchExport = () => {
      if (selectedRecords.value.length === 0) {
        ElMessage.warning('请选择要导出的记录')
        return
      }
      
      ElMessage.success(`已导出 ${selectedRecords.value.length} 条记录`)
    }
    
    // 选择变化
    const handleSelectionChange = (selection) => {
      selectedRecords.value = selection
    }
    
    // 获取渠道标签
    const getChannelTag = (channel) => {
      const tagMap = {
        'online': 'primary',
        'offline': 'success',
        'thirdparty': 'warning'
      }
      return tagMap[channel] || 'info'
    }
    
    // 获取渠道文本
    const getChannelText = (channel) => {
      const textMap = {
        'online': '线上',
        'offline': '线下',
        'thirdparty': '第三方'
      }
      return textMap[channel] || '未知'
    }
    
    // 获取状态类型
    const getStatusType = (status) => {
      const statusMap = {
        'completed': 'success',
        'processing': 'warning',
        'cancelled': 'info'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'completed': '已完成',
        'processing': '处理中',
        'cancelled': '已取消'
      }
      return statusMap[status] || '未知'
    }
    
    // 分页处理
    const handleSizeChange = (val) => {
      pageSize.value = val
      loadData()
    }
    
    const handleCurrentChange = (val) => {
      currentPage.value = val
      loadData()
    }
    
    onMounted(() => {
      loadData()
      initCharts()
    })
    
    return {
      tableLoading,
      currentPage,
      pageSize,
      total,
      showAddOrder,
      selectedRecords,
      salesTrendChart,
      categorySalesChart,
      hotProductsChart,
      channelComparisonChart,
      filterForm,
      salesStats,
      categories,
      salesList,
      handleFilter,
      resetFilter,
      loadData,
      generateReport,
      exportData,
      viewDetail,
      editOrder,
      printOrder,
      batchExport,
      handleSelectionChange,
      getChannelTag,
      getChannelText,
      getStatusType,
      getStatusText,
      handleSizeChange,
      handleCurrentChange
    }
  }
})
</script>

<style scoped>
.sales-report {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left h2 {
  margin: 0 0 5px 0;
  color: #2563eb;
}

.header-left p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.stats-overview {
  margin-bottom: 20px;
}

.stat-card {
  .stat-content {
    display: flex;
    align-items: center;
    
    .stat-icon {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16px;
      
      &.total {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
      }
      
      &.revenue {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        color: white;
      }
      
      &.average {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        color: white;
      }
      
      &.customers {
        background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
        color: white;
      }
      
      .el-icon {
        font-size: 24px;
      }
    }
    
    .stat-info {
      flex: 1;
      
      .stat-number {
        font-size: 24px;
        font-weight: bold;
        color: #333;
        margin-bottom: 4px;
      }
      
      .stat-label {
        font-size: 14px;
        color: #666;
        margin-bottom: 4px;
      }
      
      .stat-trend {
        font-size: 12px;
        display: flex;
        align-items: center;
        
        &.up {
          color: #67C23A;
        }
        
        &.down {
          color: #F56C6C;
        }
        
        .el-icon {
          margin-right: 2px;
        }
      }
    }
  }
}

.filter-section {
  margin-bottom: 20px;
}

.charts-section {
  margin-bottom: 20px;
}

.chart-card {
  .chart-container {
    height: 300px;
  }
}

.table-section {
  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .table-actions {
    display: flex;
    gap: 10px;
  }
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .header-right {
    width: 100%;
    display: flex;
    gap: 10px;
  }
  
  .stats-overview {
    .el-col {
      margin-bottom: 20px;
    }
  }
  
  .charts-section {
    .el-col {
      margin-bottom: 20px;
    }
  }
}
</style> 